# app/api/upload/utils.py

import os
import uuid
import shutil
from typing import List, Dict, Any
from fastapi import UploadFile

from config.settings import settings
from app.core.oss_service import oss_service

def validate_file_extension(filename: str) -> bool:
    """验证文件扩展名是否支持"""
    if not filename:
        return False
    
    ext = os.path.splitext(filename)[1].lower()
    all_extensions = []
    for extensions in settings.ALLOWED_EXTENSIONS.values():
        all_extensions.extend(extensions)
    return ext in all_extensions

def get_file_type(filename: str) -> str:
    """获取文件类型"""
    ext = os.path.splitext(filename)[1].lower()
    for file_type, extensions in settings.ALLOWED_EXTENSIONS.items():
        if ext in extensions:
            return file_type
    return "unknown"

def save_upload_file(upload_file: UploadFile, knowledge_base: str = "default") -> Dict[str, Any]:
    """保存上传的文件到本地和阿里云OSS，上传后删除本地文件"""
    # 创建上传目录
    os.makedirs(settings.UPLOAD_FOLDER, exist_ok=True)
    
    # 根据文件类型创建子目录
    file_type = get_file_type(upload_file.filename)
    if file_type == "document":
        sub_dir = "documents"
    elif file_type == "image":
        sub_dir = "images"
    elif file_type == "video":
        sub_dir = "videos"
    else:
        sub_dir = "temp"
    
    upload_dir = os.path.join(settings.UPLOAD_FOLDER, sub_dir)
    os.makedirs(upload_dir, exist_ok=True)
    
    # 生成唯一文件名
    file_ext = os.path.splitext(upload_file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_ext}"
    file_path = os.path.join(upload_dir, unique_filename)
    
    # 保存文件到本地
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(upload_file.file, buffer)
    
    # 上传文件到阿里云OSS
    oss_result = oss_service.upload_file(file_path, file_type, knowledge_base)
    
    return {
        'local_path': file_path,
        'file_type': file_type,
        'oss_result': oss_result
    } 